package com.wcx.flume.interceptor;

import com.alibaba.fastjson.JSON;
import org.apache.flume.Context;
import org.apache.flume.Event;
import org.apache.flume.interceptor.Interceptor;

import java.nio.charset.StandardCharsets;
import java.util.Iterator;
import java.util.List;


/**
 * 项目: flume
 * <p>
 * 功能描述:
 *
 * @author: WuChengXing
 * @create: 2020-12-16 09:02
 **/
public class LogInterceptor implements Interceptor {

    @Override
    public void initialize() {

    }

    @Override
    public Event intercept(Event event) {
        byte[] body = event.getBody();
        String log = new String(body, StandardCharsets.UTF_8);
        if (JSONUtils.isJSONValidate(log)) {
            return event;
        } else {
            return null;
        }
    }

    /**
     * 增强for移除不掉元素，需要用迭代器
     *
     * @param list
     * @return
     */
    @Override
    public List<Event> intercept(List<Event> list) {
        list.removeIf(next -> intercept(next) == null);
        return list;
    }

    public static class Builder implements Interceptor.Builder {
        @Override
        public Interceptor build() {
            return new LogInterceptor();
        }

        @Override
        public void configure(Context context) {

        }
    }

    @Override
    public void close() {

    }
}

